import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/db/repository/LocalConversationRepository.dart';
import 'package:easy_chat_app/commons/db/service/LocalConversationService.dart';
import 'package:easy_chat_app/commons/model/AppUserDetail.dart';
import 'package:easy_chat_app/commons/model/GetFriendRequestListResultData.dart';
import 'package:easy_chat_app/commons/utils/HttpUtils.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/widget/UserHeadPortrait.dart';
import 'package:easy_chat_app/mobile/constants/MobileAppGlobalConstants.dart';
import 'package:easy_chat_app/mobile/page/MobileChatPage.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

class MobileFriendRequestListPageParams {
  List<GetFriendRequestListResultDataFriendRequestView>? friendRequestViewList;

  MobileFriendRequestListPageParams.create({this.friendRequestViewList});
}

class MobileFriendRequestListPageChangeNotifier extends ChangeNotifier {
  List<GetFriendRequestListResultDataFriendRequestView> friendRequestViewList =
      [];

  Future<void> reload() async {
    friendRequestViewList =
        (await HttpUtils.getFriendRequestList()).data?.friendRequestViewList ??
            [];
    notifyListeners();
  }
}

class MobileFriendRequestListPage extends StatelessWidget {
  final Logger logger = Logger();

  MobileFriendRequestListPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<AppUserDetailChangeNotifier>(
        builder: (context, appUserDetailChangeNotifier, child) {
      AppUserDetail appUserDetail =
          appUserDetailChangeNotifier.getAppUserDetail();

      return MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) {
            MobileFriendRequestListPageParams pageParams =
                RouteUtils.currentRouteSettings().arguments
                    as MobileFriendRequestListPageParams;
            var result = MobileFriendRequestListPageChangeNotifier();
            result.friendRequestViewList =
                pageParams.friendRequestViewList ?? [];
            // 修改已读状态
            changeFriendRequestReadStatus(
                pageParams.friendRequestViewList ?? [], appUserDetail);
            return result;
          })
        ],
        builder: (context, child) {
          var mobileFriendRequestListPageChangeNotifier =
              context.watch<MobileFriendRequestListPageChangeNotifier>();
          return Scaffold(
            appBar: AppBar(
              title: const Text("新的朋友"),
              centerTitle: true,
              surfaceTintColor: MobileAppGlobalConstants.appBarSurfaceTintColor,
              backgroundColor: MobileAppGlobalConstants.appBarBackgroundColor,
            ),
            body: friendRequestList(
                mobileFriendRequestListPageChangeNotifier, appUserDetail),
          );
        },
      );
    });
  }

  Widget friendRequestList(
      MobileFriendRequestListPageChangeNotifier
          mobileFriendRequestListPageChangeNotifier,
      AppUserDetail appUserDetail) {
    var friendRequestViewList =
        mobileFriendRequestListPageChangeNotifier.friendRequestViewList;
    return ListView.builder(
        itemCount: friendRequestViewList.length,
        itemBuilder: (context, index) {
          GetFriendRequestListResultDataFriendRequestView item =
              friendRequestViewList[index];
          GetFriendRequestListResultDataUserView otherUser = item.targetUser!;

          if (appUserDetail.id == item.targetUserId) {
            otherUser = item.fromUser!;
          }
          String remarkText = "${item.remark}";
          if (appUserDetail.id == item.fromUserId) {
            remarkText = "我:${item.remark}";
          }
          return GestureDetector(
            onTap: () {
              onTapFriendRequest(mobileFriendRequestListPageChangeNotifier,
                  item, appUserDetail);
            },
            child: Container(
              margin: const EdgeInsets.only(left: 15),
              height: 60,
              decoration: const BoxDecoration(
                  border: Border(
                      bottom:
                          BorderSide(color: Color.fromRGBO(229, 229, 229, 1)))),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  UserHeadPortrait.network(
                      size: 40,
                      userCode: otherUser.code!,
                      userHeadPortrait: otherUser.headPortrait!,
                      userHeadPortraitStoreType:
                          otherUser.headPortraitStoreType!),
                  const SizedBox(
                    width: 15,
                  ),
                  Expanded(
                      child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "${otherUser.nickname}",
                        style:
                            const TextStyle(fontSize: 16, color: Colors.black),
                      ),
                      Text(
                        remarkText,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                            fontSize: 14,
                            color: Color.fromRGBO(133, 133, 133, 1)),
                      )
                    ],
                  )),
                  friendRequestStatusWidget(item, appUserDetail)
                ],
              ),
            ),
          );
        });
  }

  Future<void> changeFriendRequestReadStatus(
      List<GetFriendRequestListResultDataFriendRequestView>
          friendRequestViewList,
      AppUserDetail appUserDetail) async {
    List<int> idList = [];
    for (var value in friendRequestViewList) {
      if (appUserDetail.id == value.targetUserId) {
        idList.add(value.id!);
      }
    }
    await HttpUtils.batchChangeReadStatus2Read(idList);
  }

  final Map<int?, String> friendRequestStatusMap = {
    0: "待处理",
    1: "已通过",
    2: "已拒绝",
    3: "已过期",
  };

  Widget friendRequestStatusWidget(
      GetFriendRequestListResultDataFriendRequestView friendRequest,
      AppUserDetail appUserDetail) {
    int? status = friendRequest.status;
    String statusText = friendRequestStatusMap[status] ?? "";
    if (friendRequest.fromUserId == appUserDetail.id) {
      return Container(
        margin: const EdgeInsets.only(right: 20),
        padding: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
        child: Text(
          statusText,
          style: const TextStyle(color: Colors.black, fontSize: 12),
        ),
      );
    } else {
      if (status == 0) {
        return Container(
          decoration: BoxDecoration(
              color: const Color.fromRGBO(242, 242, 242, 1),
              borderRadius: BorderRadius.circular(3)),
          margin: const EdgeInsets.only(right: 20),
          padding:
              const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
          child: const Text(
            "查看",
            style: TextStyle(color: Colors.black),
          ),
        );
      } else {
        return Container(
          margin: const EdgeInsets.only(right: 20),
          padding:
              const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
          child: Text(
            statusText,
            style: const TextStyle(color: Colors.black, fontSize: 12),
          ),
        );
      }
    }
  }

  Future<void> onTapFriendRequest(
      MobileFriendRequestListPageChangeNotifier
          mobileFriendRequestListPageChangeNotifier,
      GetFriendRequestListResultDataFriendRequestView friendRequest,
      AppUserDetail appUserDetail) async {
    var otherUser = friendRequest.fromUser;
    if (friendRequest.fromUserId == appUserDetail.id) {
      otherUser = friendRequest.targetUser!;
    }
    bool isContact =
        (await HttpUtils.checkIsContact(otherUser!.id!)).data ?? false;
    if (isContact) {
      var localConversation =
          await LocalConversationService.syncConversation2Local(
              LocalConversationTypeConstants.general, otherUser.id, null);
      await RouteUtils.route2MobileChatPage(
        MobileChatPageParams(
            contactUserId: otherUser.id,
            contactUserCode: otherUser.code,
            contactUserNickname: otherUser.nickname,
            contactUserHeadPortrait: otherUser.headPortrait,
            contactUserHeadPortraitStoreType: otherUser.headPortraitStoreType,
            currentUserId: appUserDetail.id!,
            currentUserCode: appUserDetail.code,
            currentUserNickName: appUserDetail.nickname,
            currentUserHeadPortrait: appUserDetail.headPortrait,
            currentUserHeadPortraitStoreType:
                appUserDetail.headPortraitStoreType,
            localConversation: localConversation),
      );
    } else {
      await RouteUtils.route2MobileFriendRequestDetailPage(friendRequest);
      await mobileFriendRequestListPageChangeNotifier.reload();
    }
  }
}
